#ifndef __CM_BASE_BYTE_BUFFER_H__
#define __CM_BASE_BYTE_BUFFER_H__

#include "Common.h"
#include "BaseNotification.h"
#include "Poco/Mutex.h"

using Poco::UInt32;
using Poco::UInt16;
using Poco::UInt8;
using Poco::FastMutex;

namespace cm_base
{
    class ByteBufferPool;

    class ByteBuffer: public BaseNotification
    {
    public:
        ByteBuffer();
        ByteBuffer(size_t len);
        ByteBuffer(const char* bytes, size_t len);
        ByteBuffer(const char* bytes); // uses strlen
        
        const char* Data() const { return bytes_ + start_; }
        size_t Length() { return end_ - start_; }
        size_t Capacity() { return size_ - start_; }

        bool ReadUInt8(UInt8& val);
        bool ReadUInt16(UInt16& val);
        bool ReadUInt32(UInt32& val);
        bool ReadString(std::string& val, size_t len); // append to val
        bool ReadBytes(char* val, size_t len);

        void WriteUInt8(UInt8 val);
        void WriteUInt16(UInt16 val);
        void WriteUInt32(UInt32 val);
        void WriteString(const std::string& val);
        void WriteBytes(const char* val, size_t len);

        void Resize(size_t size);
        void Shift(size_t size);

        void reset();

        void setLength(size_t length){ end_ += length; }
        void increaseRef();
        void decreaseRef();

        ByteBufferPool* getParent();
        void setParent(ByteBufferPool* parent);

    protected:
         virtual ~ByteBuffer();
         FastMutex m_mutex;
         ByteBufferPool* m_parent;
         int m_ref_cnt;

    private:
        char* bytes_;
        size_t size_;
        size_t start_;
        size_t end_;
    };

} // namespace cm_base

#endif // __BYTE_BUFFER_H__
